/*
  * Copyright (c) 2022 Huawei Device Co., Ltd.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
    *
  * http://www.apache.org/licenses/LICENSE-2.0
    *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
import { base64Encode } from '../lib/btoa';
import { RequestInterceptors } from "../connection";
import { Errback } from "../lib/errback";
import  {RequestOptions,ArangojsResponse,ArangojsError} from "../lib/request.node"
import NetHttp from "./net_http";

export const isBrowser = true;

export function createRequest( baseUrl:string,agentOptions: RequestInterceptors,agent?:any){
    const base = new URL(baseUrl);
    const auth = base64Encode(`${base.username || "root"}:${base.password}`);
    base.username = "";
    base.password = "";
    const options = agentOptions // TODO 是否使用omit剔除 omit(agentOptions,["maxSockets"])
    return function request ({method,url:reqUrl,headers,body,timeout,expectBinary}:RequestOptions,cb:Errback<ArangojsResponse>){
        const url = new URL(reqUrl.pathname,base);
        if(base.search || reqUrl.search){
            url.search = reqUrl.search?`${base.search}${base.search?"&":""}${reqUrl.search.slice(1)}`:base.search; // TODO 注意“&”要严格按照标准格式
        }
        if(!headers["authorization"]){
            headers["authorization"] = `Basic ${auth}}`;
        }

        let callback:Errback<ArangojsResponse> = (err,res) => {
            callback = () => undefined;
            cb(err,res);
        }

        const req = NetHttp( {
            useXDR: true,
            withCredentials: true,
            ...options,
            responseType: expectBinary,
            url: String(url),
            body,
            method,
            headers,
            timeout,
        },(err: Error | null, res?: any) => {
            if (!err) {


                const response = res as ArangojsResponse;

                // @ts-ignore
                response.request = req;
                if (!response.body) response.body = "";
                if (options.after) {
                    options.after(null, response);
                }
                callback(null, response as ArangojsResponse);
            } else {
                const error = err as ArangojsError;
                if (options.after) {
                    options.after(error);
                }
                callback(error);
            }
        })

    }

}

